import { createCanvas } from 'canvas'


/**
 * 生成随机的4位字母验证码
 * @returns code值和base64的验证码图片
 */
export const generateCanvas = () => {
  const length = 4
  const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  const colors = ['#EE3B3B', '#FF8C00', '#FFD700', '#00BFFF', '#9932CC', '#8B008B', '#708090']

  let codeMap = new Map<any, { color: string, str: string, fontSize: number, index: number }>()
  let code = ''

  for (let i = 0; i < length; i++) {
    const idx = Math.floor(Math.random() * chars.length)
    code += chars[idx]
    codeMap.set(i, { color: colors[Math.floor(Math.random() * colors.length)], str: chars[idx], fontSize: Math.floor(Math.random() * 16 + 15), index: i })
  }

  const canvas = createCanvas(100, 50)
  const ctx = canvas.getContext('2d')
  ctx.fillStyle = '#fff' // 设置背景色
  ctx.fillRect(0, 0, 100, 50)

  codeMap.forEach((value) => {
    ctx.font = `${value.fontSize}px Arial`
    ctx.fillStyle = value.color
    ctx.fillText(value.str, 20 * value.index + Math.floor(Math.random() * 6 + 5), 35)
  })

  for (let i = 0; i < 6; i++) {
    const x1 = Math.floor(Math.random() * 100)
    const y1 = Math.floor(Math.random() * 50)
    const x2 = Math.floor(Math.random() * 100)
    const y2 = Math.floor(Math.random() * 50)
    ctx.beginPath()
    ctx.moveTo(x1, y1)
    ctx.lineTo(x2, y2)
    ctx.strokeStyle = colors[Math.floor(Math.random() * colors.length)]
    ctx.stroke()
  }

  const image = canvas.toDataURL()

  return { image, code }
}